<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>推流页面</title>
</head>
<body>
<h2>🎥 推流中...</h2>
<video id="localVideo" style="width: 800px;height: 800px" autoplay muted playsinline controls></video>

<script>
    const room = new URLSearchParams(location.search).get("room") || "default";
    const ws = new WebSocket(`ws://${location.host}/ws/publish?room=${room}`);
    const pc = new RTCPeerConnection({
        // iceServers: [{ urls: "stun:127.0.0.1:3478" }]
        iceServers: [],
        iceTransportPolicy:"all"
    });
    pc.oniceconnectionstatechange = () => {
        console.log("ICE 状态：", pc.iceConnectionState);
    };
    const localVideo = document.getElementById("localVideo");
    let remoteDescSet = false;
    const pendingCandidates = [];

    navigator.mediaDevices.getDisplayMedia({ video: true, audio: false }).then(stream => {
        localVideo.srcObject = stream;

        stream.getTracks().forEach(track => {
            console.log("添加了")
            pc.addTrack(track, stream);
        });

        pc.createOffer().then(offer => {
            pc.setLocalDescription(offer);
            ws.send(JSON.stringify({ type: "offer", sdp: offer.sdp }));
        });
    });
    // const dataChannel =  pc.createDataChannel("mataInfo",null)
    // dataChannel.onopen(()=>{
    //     console.log("open")
    //    setInterval(()=>{
    //        dataChannel.send(JSON.stringify({data:123,info:123}))
    //    })
    // })
    pc.onicecandidate = (event) => {
        if (event.candidate) {
            ws.send(JSON.stringify({ type: "candidate", candidate: event.candidate }));
        }
    };

    ws.onmessage = async (msg) => {
        const data = JSON.parse(msg.data);

        if (data.type === "answer") {
            await pc.setRemoteDescription({ type: "answer", sdp: data.sdp });
            remoteDescSet = true;
            pendingCandidates.forEach(candidate => pc.addIceCandidate(candidate));
        } else if (data.type === "candidate") {
            if (remoteDescSet) {
                await pc.addIceCandidate(data.candidate);
            } else {
                pendingCandidates.push(data.candidate);
            }
        }
    };
    window.addEventListener("beforeunload", () => {
        ws.close();
        pc.close();
    });
</script>
</body>
</html>
